#!/usr/bin/env node

const { exec } = require('child_process');
const fs = require('fs');
const path = require('path');
const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
);

class TestRunner {
  constructor() {
    this.testDir = path.join(__dirname, '..');
    this.results = [];
    this.startTime = Date.now();
  }

  async run() {
    console.log('\n🚀 AI Agent平台自动化测试执行器');
    console.log('=====================================\n');

    this.showMenu();
  }

  showMenu() {
    console.log('📋 请选择测试执行模式:');
    console.log('');
    console.log('1. 🏃‍♂️  快速测试 - 核心功能验证');
    console.log('2. 🔍 完整测试 - 所有功能测试');
    console.log('3. 🌐 兼容性测试 - 环境和浏览器兼容性');
    console.log('4. 🎯 单一模块测试 - 选择特定模块');
    console.log('5. 🐛 调试模式 - 可视化调试');
    console.log('6. 📊 生成测试报告');
    console.log('7. 🧹 清理测试数据');
    console.log('8. 📖 查看测试状态');
    console.log('0. 🚪 退出');
    console.log('');

    rl.question('请输入选项 (0-8): ', (answer) => {
      this.handleChoice(answer);
    });
  }

  async handleChoice(choice) {
    switch (choice) {
      case '1':
        await this.runQuickTests();
        break;
      case '2':
        await this.runFullTests();
        break;
      case '3':
        await this.runCompatibilityTests();
        break;
      case '4':
        await this.runModuleTests();
        break;
      case '5':
        await this.runDebugMode();
        break;
      case '6':
        await this.generateReports();
        break;
      case '7':
        await this.cleanupTests();
        break;
      case '8':
        this.showTestStatus();
        break;
      case '0':
        console.log('\n👋 再见！');
        rl.close();
        process.exit(0);
        break;
      default:
        console.log('\n❌ 无效选项，请重新选择');
        this.showMenu();
    }
  }

  async runQuickTests() {
    console.log('\n🏃‍♂️  执行快速测试...\n');

    const quickTests = [
      {
        name: '环境检查',
        command: 'node scripts/test-compatibility.js',
        description: '检查测试环境和依赖'
      },
      {
        name: '基础认证测试',
        command: 'npx playwright test tests/e2e/auth/auth.spec.ts --grep "TC-001|TC-005" --reporter=list',
        description: '用户登录和登出功能'
      },
      {
        name: 'Agent基础测试',
        command: 'npx playwright test tests/e2e/agents/agent-management.spec.ts --grep "TC-101|TC-105" --reporter=list',
        description: 'Agent列表和创建功能'
      }
    ];

    for (const test of quickTests) {
      console.log(`🧪 ${test.name}: ${test.description}`);
      await this.executeCommand(test.command);
    }

    console.log('\n✅ 快速测试完成！');
    this.waitForContinue();
  }

  async runFullTests() {
    console.log('\n🔍 执行完整测试套件...\n');

    const fullTests = [
      {
        name: '兼容性检查',
        command: 'npm run test:compatibility',
        description: '环境和依赖兼容性'
      },
      {
        name: '认证功能测试',
        command: 'npx playwright test tests/e2e/auth/ --reporter=list',
        description: '完整的认证系统测试'
      },
      {
        name: 'Agent管理测试',
        command: 'npx playwright test tests/e2e/agents/ --reporter=list',
        description: 'Agent CRUD和管理功能'
      },
      {
        name: '对话功能测试',
        command: 'npx playwright test tests/e2e/conversations/ --reporter=list',
        description: '对话和消息功能'
      }
    ];

    for (const test of fullTests) {
      console.log(`🧪 ${test.name}: ${test.description}`);
      await this.executeCommand(test.command);
    }

    console.log('\n✅ 完整测试套件执行完成！');
    this.waitForContinue();
  }

  async runCompatibilityTests() {
    console.log('\n🌐 执行兼容性测试...\n');

    console.log('🧪 环境兼容性测试');
    await this.executeCommand('npm run test:compatibility');

    console.log('\n🧪 跨浏览器测试');
    await this.executeCommand('npx playwright test tests/e2e/auth/auth.spec.ts --grep "TC-001" --project=chromium,firefox,webkit --reporter=list');

    console.log('\n✅ 兼容性测试完成！');
    this.waitForContinue();
  }

  async runModuleTests() {
    console.log('\n🎯 选择测试模块:');
    console.log('');
    console.log('1. 🔐 认证模块');
    console.log('2. 🤖 Agent管理模块');
    console.log('3. 💬 对话功能模块');
    console.log('4. 📊 监控功能模块');
    console.log('5. 🔧 返回主菜单');
    console.log('');

    rl.question('请选择模块 (1-5): ', async (answer) => {
      switch (answer) {
        case '1':
          await this.executeModuleTest('auth', '认证模块');
          break;
        case '2':
          await this.executeModuleTest('agents', 'Agent管理模块');
          break;
        case '3':
          await this.executeModuleTest('conversations', '对话功能模块');
          break;
        case '4':
          await this.executeModuleTest('monitoring', '监控功能模块');
          break;
        case '5':
          this.showMenu();
          return;
        default:
          console.log('\n❌ 无效选项');
          this.runModuleTests();
      }
    });
  }

  async executeModuleTest(module, moduleName) {
    console.log(`\n🧪 执行${moduleName}测试...\n`);

    const testPath = `tests/e2e/${module}/`;
    const fs = require('fs');
    const testDir = path.join(__dirname, '..', testPath);

    if (fs.existsSync(testDir)) {
      await this.executeCommand(`npx playwright test ${testPath} --reporter=list`);
      console.log(`\n✅ ${moduleName}测试完成！`);
    } else {
      console.log(`\n❌ ${moduleName}测试不存在`);
    }

    this.waitForContinue();
  }

  async runDebugMode() {
    console.log('\n🐛 调试模式选项:');
    console.log('');
    console.log('1. 👁️  可视化调试 (headed mode)');
    console.log('2. 🔍 交互式调试 (debug mode)');
    console.log('3. 🎨 UI模式测试');
    console.log('4. 📹 录制测试视频');
    console.log('5. 🔧 返回主菜单');
    console.log('');

    rl.question('请选择调试模式 (1-5): ', async (answer) => {
      switch (answer) {
        case '1':
          await this.executeCommand('npx playwright test --headed');
          break;
        case '2':
          await this.executeCommand('npx playwright test --debug');
          break;
        case '3':
          await this.executeCommand('npx playwright test --ui');
          break;
        case '4':
          await this.executeCommand('npx playwright test --video=on');
          break;
        case '5':
          this.showMenu();
          return;
        default:
          console.log('\n❌ 无效选项');
          this.runDebugMode();
      }
      this.waitForContinue();
    });
  }

  async generateReports() {
    console.log('\n📊 生成测试报告...\n');

    const reports = [
      {
        name: 'HTML测试报告',
        command: 'npm run test:e2e:report',
        description: '可视化测试报告'
      },
      {
        name: '兼容性报告',
        command: 'node scripts/test-compatibility.js',
        description: '环境和兼容性检查报告'
      }
    ];

    for (const report of reports) {
      console.log(`📄 ${report.name}: ${report.description}`);
      await this.executeCommand(report.command);
    }

    console.log('\n📋 报告位置:');
    console.log('   - HTML报告: playwright-report/index.html');
    console.log('   - 兼容性报告: test-results/compatibility-report.json');
    console.log('   - JSON报告: test-results/test-results.json');

    this.waitForContinue();
  }

  async cleanupTests() {
    console.log('\n🧹 清理测试数据...\n');

    const cleanupCommands = [
      'rm -rf test-results',
      'rm -rf playwright-report',
      'rm -rf screenshots',
      'rm -rf videos'
    ];

    for (const command of cleanupCommands) {
      try {
        await this.executeCommand(command, { silent: true });
      } catch (error) {
        console.log(`⚠️  清理命令失败: ${command}`);
      }
    }

    console.log('\n✅ 测试数据清理完成！');
    this.waitForContinue();
  }

  showTestStatus() {
    console.log('\n📊 当前测试状态:\n');

    // 检查各种测试文件和目录
    const checks = [
      {
        name: '测试配置文件',
        files: ['playwright.config.ts', 'tests/.env.test']
      },
      {
        name: '测试用例文件',
        files: [
          'tests/e2e/auth/auth.spec.ts',
          'tests/e2e/agents/agent-management.spec.ts',
          'tests/e2e/conversations/conversation.spec.ts'
        ]
      },
      {
        name: '测试工具',
        files: ['tests/utils/test-helpers.ts', 'tests/utils/api-mock.ts']
      },
      {
        name: '测试报告目录',
        dirs: ['test-results', 'playwright-report']
      }
    ];

    checks.forEach(check => {
      console.log(`📁 ${check.name}:`);

      if (check.files) {
        check.files.forEach(file => {
          const fullPath = path.join(__dirname, '..', file);
          const exists = fs.existsSync(fullPath);
          console.log(`   ${exists ? '✅' : '❌'} ${file}`);
        });
      }

      if (check.dirs) {
        check.dirs.forEach(dir => {
          const fullPath = path.join(__dirname, '..', dir);
          const exists = fs.existsSync(fullPath);
          console.log(`   ${exists ? '✅' : '❌'} ${dir}/`);
        });
      }

      console.log('');
    });

    this.waitForContinue();
  }

  async executeCommand(command, options = {}) {
    return new Promise((resolve) => {
      console.log(`🔧 执行命令: ${command}\n`);

      const childProcess = exec(command, {
        cwd: this.testDir,
        timeout: options.timeout || 300000
      });

      if (!options.silent) {
        childProcess.stdout?.on('data', (data) => {
          process.stdout.write(data);
        });

        childProcess.stderr?.on('data', (data) => {
          process.stderr.write(data);
        });
      }

      childProcess.on('close', (code) => {
        if (code === 0) {
          console.log('\n✅ 命令执行成功');
        } else {
          console.log(`\n❌ 命令执行失败，退出码: ${code}`);
        }
        resolve();
      });

      childProcess.on('error', (error) => {
        console.error(`\n❌ 命令执行错误: ${error.message}`);
        resolve();
      });
    });
  }

  waitForContinue() {
    console.log('\n');
    rl.question('按回车键继续...', () => {
      this.showMenu();
    });
  }
}

// 启动测试运行器
const runner = new TestRunner();
runner.run().catch(console.error);